<template>
  <div class="question-management">
    <el-card shadow="hover" class="questions-card">
      <!-- 搜索和过滤组件 -->
      <div class="filter-bar">
        <el-input
          v-model="questionKeyword"
          placeholder="搜索问题"
          class="search-input"
          clearable
          @keyup.enter="getAllQuestions"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="questionStatus" placeholder="状态" style="width: 120px; margin-left: 10px;">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="待审核" :value="0"></el-option>
          <el-option label="已发布" :value="1"></el-option>
          <el-option label="已解决" :value="2"></el-option>
          <el-option label="已关闭" :value="3"></el-option>
          <el-option label="被拒绝" :value="4"></el-option>
        </el-select>
        
        <el-button type="primary" @click="getAllQuestions" style="margin-left: 10px;">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>
      
      <!-- 问题列表 -->
      <el-table
        v-loading="loading"
        :data="questions"
        style="width: 100%; margin-top: 20px;"
        border
        @selection-change="handleQuestionSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="提问者" width="120" />
        <el-table-column prop="viewCount" label="浏览量" width="90" sortable />
        <el-table-column prop="answerCount" label="回答数" width="90" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getQuestionStatusTag(scope.row.status)">
              {{ getQuestionStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="navigateToDetail(scope.row.id)"
            >查看</el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              size="small"
              plain
              @click="reviewQuestion(scope.row.id, 1)"
            >通过</el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              size="small"
              plain
              @click="showRejectDialog(scope.row.id)"
            >拒绝</el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="deleteQuestion(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <QuestionBatchActions
        v-if="selectedQuestions.length > 0"
        :count="selectedQuestions.length"
        @batch-approve="batchApproveQuestions"
        @batch-reject="showBatchRejectDialog"
        @batch-delete="batchDeleteQuestions"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 拒绝问题对话框 -->
    <el-dialog
      title="拒绝问题"
      v-model="rejectDialogVisible"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝理由" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRejectQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { 
  getAllQuestions as apiGetAllQuestions,
  reviewQuestion as apiReviewQuestion,
  deleteQuestion as apiDeleteQuestion,
  batchDeleteQuestions as apiBatchDeleteQuestions
} from '../../api/admin';
import QuestionBatchActions from './QuestionBatchActions.vue';

const props = defineProps({});
const emit = defineEmits(['refresh']);
const router = useRouter();

// 问题管理相关
const questions = ref([]);
const questionKeyword = ref('');
const questionStatus = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedQuestions = ref([]);
const loading = ref(false);

// 拒绝问题对话框
const rejectDialogVisible = ref(false);
const rejectForm = ref({
  questionId: null,
  reason: ''
});

// 获取所有问题列表
const getAllQuestions = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: questionKeyword.value,
      status: questionStatus.value
    };
    
    const response = await apiGetAllQuestions(params);
    if (response.code === 200) {
      questions.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取问题列表失败');
    }
  } catch (error) {
    console.error('获取问题列表失败:', error);
    ElMessage.error('获取问题列表失败: ' + (error.message || '未知错误'));
    questions.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 问题状态标签和文本
const getQuestionStatusTag = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  };
  return statusMap[status] || 'info';
};

const getQuestionStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已发布',
    2: '已解决',
    3: '已关闭',
    4: '被拒绝'
  };
  return statusMap[status] || '未知';
};

// 处理问题选择变化
const handleQuestionSelectionChange = (selection) => {
  selectedQuestions.value = selection;
};

// 处理问题分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getAllQuestions();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getAllQuestions();
};

// 显示拒绝问题对话框
const showRejectDialog = (questionId) => {
  rejectForm.value.questionId = questionId;
  rejectForm.value.reason = '';
  rejectDialogVisible.value = true;
};

// 确认拒绝问题
const confirmRejectQuestion = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请输入拒绝理由');
    return;
  }
  
  try {
    loading.value = true;
    
    // 区分单个拒绝和批量拒绝
    if (rejectForm.value.questionId) {
      // 单个问题拒绝
      const response = await apiReviewQuestion(
        rejectForm.value.questionId,
        4,
        rejectForm.value.reason
      );
      
      if (response.code === 200) {
        ElMessage.success('问题已拒绝');
        rejectDialogVisible.value = false;
        getAllQuestions();
      } else {
        ElMessage.error(response.message || '拒绝问题失败');
      }
    } else {
      // 批量拒绝
      if (selectedQuestions.value.length === 0) {
        ElMessage.warning('请选择要拒绝的问题');
        loading.value = false;
        return;
      }
      
      const promises = selectedQuestions.value.map(question => 
        apiReviewQuestion(question.id, 4, rejectForm.value.reason)
      );
      
      try {
        await Promise.all(promises);
        ElMessage.success(`已拒绝${selectedQuestions.value.length}个问题`);
        rejectDialogVisible.value = false;
        getAllQuestions();
      } catch (batchError) {
        console.error('批量拒绝问题失败:', batchError);
        ElMessage.error('批量拒绝问题失败: ' + (batchError.message || '未知错误'));
      }
    }
  } catch (error) {
    console.error('拒绝问题失败:', error);
    ElMessage.error('拒绝问题失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 显示批量拒绝对话框
const showBatchRejectDialog = () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请选择要拒绝的问题');
    return;
  }
  
  rejectForm.value.questionId = null; // 批量拒绝时使用selectedQuestions
  rejectForm.value.reason = '';
  rejectDialogVisible.value = true;
};

// 审核问题
const reviewQuestion = async (id, status) => {
  if (status === 4) {
    showRejectDialog(id);
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要通过此问题吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const response = await apiReviewQuestion(id, status);
    if (response.code === 200) {
      ElMessage.success('问题审核通过');
      getAllQuestions();
    } else {
      ElMessage.error(response.message || '问题审核失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('问题审核失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量通过问题
const batchApproveQuestions = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请选择要通过的问题');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要通过选中的${selectedQuestions.value.length}个问题吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const promises = selectedQuestions.value.map(question => apiReviewQuestion(question.id, 1));
    await Promise.all(promises);
    
    ElMessage.success(`已通过${selectedQuestions.value.length}个问题`);
    getAllQuestions();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量通过问题失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 删除问题
const deleteQuestion = async (id) => {
  try {
    loading.value = true;
    await ElMessageBox.confirm('确定要删除此问题吗？此操作不可恢复!', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    const response = await apiDeleteQuestion(id);
    if (response.code === 200) {
      ElMessage.success('问题已删除');
      getAllQuestions();
    } else {
      ElMessage.error(response.message || '删除问题失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除问题失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除问题
const batchDeleteQuestions = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请选择要删除的问题');
    return;
  }
  
  try {
    loading.value = true;
    await ElMessageBox.confirm(`确定要删除选中的${selectedQuestions.value.length}个问题吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    const questionIds = selectedQuestions.value.map(question => question.id);
    const response = await apiBatchDeleteQuestions(questionIds);
    
    if (response.code === 200) {
      ElMessage.success(`已删除${response.data || selectedQuestions.value.length}个问题`);
      getAllQuestions();
    } else {
      ElMessage.error(response.message || '批量删除问题失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除问题失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 导航到问题详情页
const navigateToDetail = (id) => {
  if (!id) {
    ElMessage.warning('问题ID不存在，无法跳转');
    return;
  }
  
  try {
    // 使用路由跳转
    router.push(`/question/${id}`);
  } catch (error) {
    console.error('页面跳转失败:', error);
    ElMessage.error('页面跳转失败');
  }
};

// 初始化
onMounted(() => {
  getAllQuestions();
});

// 暴露方法给父组件
defineExpose({
  getAllQuestions
});
</script>

<style scoped>
.question-management {
  width: 100%;
}

.questions-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-bar .el-button,
  .filter-bar .el-select {
    width: 100% !important;
    margin-left: 0 !important;
  }
}
</style> 